/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Salesman;

import Salesman.Data.DataProvider;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

/**
 *
 */
public class TSPGreedy extends TSPEngine {

    private Stack<City> route;
    private List<City> inSimulationCities;
    private Distances distances;
    private double distance;
    private City start;

    @Override
    public void start(City city) {
        start = city;
        distances = DataProvider.getDistances();
        inSimulationCities = DataProvider.getInSimulationCities();

        route = new Stack<City>();
        distance = 0;
        route.push(city);
        inSimulationCities.remove(city);
        resetCounter();
    }

    @Override
    public String toString() {
        return "Greedy Algorithmus";
    }

    @Override
    public boolean next() {

        if (inSimulationCities.isEmpty()) {
            if (start == null) {
                return false;
            } else {
                inSimulationCities.add(start);
                start = null;
            }
        }

        List<Double> ls = new ArrayList<Double>();

        for (City c : inSimulationCities) {
            ls.add(distances.get(DataProvider.getCityData().indexOf(route.peek()),
                    DataProvider.getCityData().indexOf(c)));
        }

        final Double way = Collections.min(ls);
        distance += way;
        City c = inSimulationCities.get(ls.indexOf(way));


        route.push(c);
        inSimulationCities.remove(c);
        incCounter();
        fireListener(new AbstractStep() {

            @Override
            public List<City> getCities() {
                return route;
            }

            @Override
            public String toString() {
                DecimalFormat f = new DecimalFormat("0.#");
                return "Route: " + routeToString() + "\n"
                        + "Teilweg: " + f.format(way) + " km\n"
                        + "Gesamtweg: " + f.format(distance) + " km\n\n";
            }
        });

        return true;
    }
}
